package com.example.familytreebe.controller;

import com.example.familytreebe.dto.FamilyNodeDTO;
import com.example.familytreebe.dto.SpouseDTO;
import com.example.familytreebe.entity.Person;
import com.example.familytreebe.entity.Relationship;
import com.example.familytreebe.service.PersonService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.format.annotation.DateTimeFormat;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDate;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("/api/persons")
public class PersonController {
    private final PersonService personService;

    @Autowired
    public PersonController(PersonService personService) {
        this.personService = personService;
    }

    @PostMapping
    public Person savePerson(@RequestBody Person person) {
        return personService.savePerson(person);
    }

    // 根据ID查询人员
    @GetMapping("/{id}")
    public ResponseEntity<?> getPersonById(@PathVariable Long id) {
        return personService.getPersonById(id)
                .map(ResponseEntity::ok) // 存在时返回200和人员数据
                .orElse(ResponseEntity.notFound().build()); // 不存在时返回404
    }

    @PostMapping("/{childId}/father/{fatherId}")
    public ResponseEntity<String> addFatherRelationship(
            @PathVariable Long childId,
            @PathVariable Long fatherId) {
        try {
            personService.addFather(childId, fatherId);
            return ResponseEntity.ok("父亲关系添加成功");
        } catch (IllegalArgumentException e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        }
    }

    @PostMapping("/{childId}/mother/{motherId}")
    public ResponseEntity<String> addMother(
            @PathVariable Long childId,
            @PathVariable Long motherId) {
        try {
            personService.addMother(childId, motherId);
            return ResponseEntity.ok("母亲关系添加成功");
        } catch (IllegalArgumentException e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        }
    }

    @GetMapping("/{personId}/relationships")
    public List<Relationship> getRelationships(@PathVariable Long personId) {
        return personService.getRelationships(personId);
    }

    // 查询所有人员
    @GetMapping
    public List<Person> getAllPersons() {
        return personService.getAllPersons();
    }

    @DeleteMapping("/relationships/{relationshipId}")
    public ResponseEntity<String> deleteRelationship(@PathVariable Long relationshipId) {
        personService.deleteRelationship(relationshipId);
        return ResponseEntity.ok("关系删除成功");
    }

    @DeleteMapping("/{personId}/relationships")
    public ResponseEntity<String> deleteRelationshipsByType(
            @PathVariable Long personId,
            @RequestParam String type) {
        personService.deleteRelationshipsByType(personId, type);
        return ResponseEntity.ok("指定类型关系已删除");
    }

    @PatchMapping("/relationships/{id}/type")  // 使用PATCH表示部分更新
    public ResponseEntity<String> updateRelationshipType(
            @PathVariable Long id,
            @RequestParam String newType) {

        try {
            personService.updateRelationshipType(id, newType);
            return ResponseEntity.ok("关系类型修改成功");
        } catch (IllegalArgumentException e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        }
    }

    @GetMapping("/{personId}/relationships/filter")
    public List<Relationship> filterRelationships(
            @PathVariable Long personId,
            @RequestParam String type
    ) {
        return personService.getRelationshipsByType(personId, type);
    }

    public ResponseEntity<List<Relationship>> getRelationshipsByType(
            @PathVariable Long personId,
            @RequestParam(required = false) String type) {  // 参数改为可选

        if (type != null) {
            return ResponseEntity.ok(
                    personService.getRelationshipsByType(personId, type)
            );
        }
        return ResponseEntity.ok(
                personService.getRelationships(personId)  // 原有方法
        );
    }

    @GetMapping("/{personId}/children")
    public List<Person> getChildren(@PathVariable Long personId) {
        return personService.getChildren(personId);
    }

    @GetMapping("/{personId}/parents")
    public List<Person> getParents(@PathVariable Long personId) {
        return personService.getParents(personId);
    }

    @GetMapping("/{personId}/spouses")
    public List<SpouseDTO> getSpouses(@PathVariable Long personId) {  // 修改返回类型
        return personService.getSpouses(personId);
    }

    @PostMapping("/{person" + "Id}/spouses/{spouseId}")
    public ResponseEntity<String> addSpouse(
            @PathVariable Long personId,
            @PathVariable Long spouseId,
            @RequestParam @DateTimeFormat(iso = DateTimeFormat.ISO.DATE) LocalDate marriageDate) {

        personService.addSpouse(personId, spouseId, marriageDate);
        return ResponseEntity.ok("配偶关系添加成功");
    }
    @PostMapping("/{personId}/brother/{brotherId}")
    public ResponseEntity<String> addBrotherRelationship(
            @PathVariable Long personId,
            @PathVariable Long brotherId) {
        try {
            personService.addBrother(personId, brotherId);
            return ResponseEntity.ok("兄弟关系添加成功");
        } catch (IllegalArgumentException e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        }
    }

    @PostMapping("/{personId}/sister/{sisterId}")
    public ResponseEntity<String> addSisterRelationship(
            @PathVariable Long personId,
            @PathVariable Long sisterId) {
        try {
            personService.addSister(personId, sisterId);
            return ResponseEntity.ok("姐妹关系添加成功");
        } catch (IllegalArgumentException e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        }
    }

    @GetMapping("/{personId}/family-tree")
    public FamilyNodeDTO getFamilyTree(@PathVariable Long personId) {
        return personService.getFamilyTree(personId);
    }

    @PutMapping("/{id}")
    public ResponseEntity<?> updatePerson(@PathVariable Long id, @RequestBody Person person) {
        try {
            Person updatedPerson = personService.updatePerson(id, person);
            return ResponseEntity.ok(updatedPerson);
        } catch (IllegalArgumentException e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        }
    }

    @DeleteMapping("/{id}")
    public ResponseEntity<String> deletePerson(@PathVariable Long id) {
        try {
            personService.deletePerson(id);
            return ResponseEntity.ok("人员信息删除成功");
        } catch (IllegalArgumentException e) {
            return ResponseEntity.badRequest().body(e.getMessage());
        }
    }
    @GetMapping("/count")
    public long countFamilyMembers() {
        return personService.countFamilyMembers();
    }
    @GetMapping("/search")
    public List<Person> searchPersons(@RequestParam(required = false) String name,
                                      @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") Date startDate,
                                      @RequestParam(required = false) @DateTimeFormat(pattern = "yyyy-MM-dd") Date endDate) {
        return personService.searchPersons(name, startDate, endDate);
    }
}

